import { type BrowserWindow, ipcMain } from "electron";
import type { WindowStateChangeArgs } from "@common/ipc-window-types.ts";

export const { registerWindowIpcInvoker } = (() => {
  /// 窗口缓存
  const winds = new Map<number, BrowserWindow>();

  ipcMain.on("window.minimize", event => winds.get(event.sender.id)?.minimize());
  ipcMain.on("window.maximize", event => winds.get(event.sender.id)?.maximize());
  ipcMain.on("window.unmaximize", event => winds.get(event.sender.id)?.unmaximize());
  ipcMain.on("window.close", event => winds.get(event.sender.id)?.close());

  ipcMain.on("window.devtools", event => {
    const webContents = winds.get(event.sender.id)?.webContents;
    webContents?.openDevTools({ mode: "detach" });
  });

  ipcMain.handle("window.get-state", event => {
    const wind = winds.get(event.sender.id);
    return getWindowState(wind);
  });

  function registerWindowIpcInvoker(wind: BrowserWindow) {
    winds.set(wind.webContents.id, wind);
    const onWindowStateChanged = getOnWindowStateChanged(wind);
    wind.on("minimize", onWindowStateChanged);
    wind.on("maximize", onWindowStateChanged);
    wind.on("unmaximize", onWindowStateChanged);
    wind.once("close", () => {
      winds.delete(wind.webContents.id);
      wind.off("minimize", onWindowStateChanged);
      wind.off("maximize", onWindowStateChanged);
      wind.off("unmaximize", onWindowStateChanged);
    });
  }

  function getOnWindowStateChanged(wind: BrowserWindow) {
    return () => {
      wind.webContents.send("window.state-changed", getWindowState(wind));
    };
  }

  function getWindowState(wind: BrowserWindow | undefined): WindowStateChangeArgs {
    return {
      maximized: wind?.isMaximized() ?? false,
    };
  }

  return {
    registerWindowIpcInvoker: registerWindowIpcInvoker,
  };
})();
